package com.zhxxfwzx.service.details;

import com.zhxxfwzx.entity.CustomUserDetails;
import com.zhxxfwzx.entity.SysUser;
import com.zhxxfwzx.service.SysUserService;
import com.zhxxfwzx.service.impl.SysUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * @Description TODO
 * @title: MyUserDetailsService
 * @Author LiJing
 * @Date: 2021/6/1210:13 下午
 * @Version 1.0
 */
@Service("myUserDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        SysUser user = sysUserService.getUserByUsername(s);
        if (user == null){
            throw new UsernameNotFoundException("该用户不存在");
        }
        return new CustomUserDetails(user.getUserId(), user.getUsername(), user.getPassword(), getUserAuthority(user.getUserId()));
    }

    /**
     * 获取用户角色权限信息
     * @param userId 用户id
     * @return
     */
    public List<GrantedAuthority> getUserAuthority(Long userId) {
        String authority = sysUserService.getUserAuthorityInfo(userId);
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
        return auths;
    }


}
